#include "LPC11XX.H"

#define LED1_ON()  (LPC_GPIO2->DATA &= ~(1<<0))
#define LED1_OFF() (LPC_GPIO2->DATA |= (1<<0))

#define LED2_ON()  (LPC_GPIO2->DATA &= ~(1<<1))
#define LED2_OFF() (LPC_GPIO2->DATA |= (1<<1))

#define KEY1_DOWN() ((LPC_GPIO3->DATA & (1<<0)) != (1<<0))
#define KEY2_DOWN() ((LPC_GPIO3->DATA & (1<<1))!=(1<<1))


void LEDInit()
{
    LPC_SYSCON->SYSAHBCLKCTRL |= (1<<16); 
    LPC_IOCON->PIO2_0 &= ~0x07;    
    LPC_IOCON->PIO2_0 |= 0x00; 
    LPC_IOCON->PIO2_1 &= ~0x07;   
    LPC_IOCON->PIO2_1 |= 0x00; 
    LPC_SYSCON->SYSAHBCLKCTRL &= ~(1<<16); 
    
    LPC_SYSCON->SYSAHBCLKCTRL |= (1<<6);    
    LPC_GPIO2->DIR |= (1<<0); 
    LPC_GPIO2->DATA |= (1<<0); 
    LPC_GPIO2->DIR |= (1<<1); 
    LPC_GPIO2->DATA |= (1<<1); 
}

void PIOINT3_IRQHandler()
{
    if((LPC_GPIO3->MIS & (1<<0))==(1<<0)) 
    {
        LED1_ON();
        while(KEY1_DOWN());
        LED1_OFF();
        LPC_GPIO3->IC = (1<<0);  
    }
    if((LPC_GPIO3->MIS & (1<<1))==(1<<1)) 
    {
        LED2_ON();
        while(KEY2_DOWN());
        LED2_OFF();
        LPC_GPIO3->IC = (1<<1);  
    }
}

int main()
{
    LEDInit();
    
    LPC_IOCON->PIO3_0 &= ~(0x07);
  LPC_GPIO3->DIR    &= ~(1<<0);
    LPC_IOCON->PIO3_1 &= ~(0x07);
    LPC_GPIO3->DIR &= ~(1<<1);
    
    LPC_GPIO3->IE |= (1<<0); 
    LPC_GPIO3->IE |= (1<<1); 
    LPC_GPIO3->IS &= ~(1<<0); 
    LPC_GPIO3->IS &= ~(1<<1); 
    LPC_GPIO3->IEV &= ~(1<<0); 
    LPC_GPIO3->IEV &= ~(1<<1); 
    NVIC_EnableIRQ(EINT3_IRQn); 
    while(1)
    {
        ;
    }
}
